import React, { Component } from "react";
import { connect } from "react-redux";
import { AdvancedTable } from "components/index";
import { Button, Modal, message } from "antd";
import Selector from "components/selector";
import { messages, queryCurrencyPrecision } from "share/common";
import moment from "moment";
import selectorData from "share/selectorData";
import EditDate from "../../../pay/template/edit-date";
import Space from "components/space";
import httpFetch from "share/httpFetch";
import menuRoute from "routes/menuRoute";
import expenseService from "../../../my-account/expense.service";
import Credential from "./credential";

class AccrualManagementRecheck extends Component {
  onSelectChange = (selectedRowKeys) => {
    let { rowSelection } = this.state;
    rowSelection.selectedRowKeys = selectedRowKeys;
    this.setState({ rowSelection });
  };

  onSelectItem = (record, selected) => {
    const { selectedData } = this.state;
    if (selected) {
      selectedData.push(record);
    } else {
      selectedData.deleteObj(record, "accruedExpenseBatchIds");
    }
    this.setState({ selectedData });
  };

  onSelectAll = (selected, selectedRows, changeRows) => {
    changeRows.map((changeRow) => this.onSelectItem(changeRow, selected));
  };

  state = {
    searchForm: [
      {
        component: (isTitle) => (
          <Selector
            allowClear={false}
            type={"setOfBooksByTenant"}
            params={{ roleType: "TENANT" }}
            entity
            onChange={(value) => this.handleChangeSetOfBook(value, isTitle)}
          />
        ),
        id: "setOfBooksId",
        judgeInTitle: true,
        label: messages("finance-10.key27") /*批次账套*/,
        initialValue: {
          setOfBooksName: this.props.company.setOfBooksName,
          id: this.props.company.setOfBooksId,
        },
        tagUnclosed: true,
        parser: (value) => ({ setOfBooksId: value ? value.id : undefined }),
        tagParser: (value) => value.setOfBooksName,
      },
      {
        id: "companyId",
        label: messages("finance-10.key28") /*批次公司*/,
        component: "Chooser",
        props: {
          type: "available_company_setOfBooks",
          labelKey: "name",
          valueKey: "id",
          single: true,
          listExtraParams: {
            enabled: true,
            setOfBooksId: this.props.company.setOfBooksId,
          },
        },
        initialValue: [{ name: this.props.company.name, id: this.props.company.id }],
        parser: (value) => ({
          companyId: value && value.length ? value[0].id : null,
        }),
      },
      {
        id: "createdBy",
        label: messages("finance-10.key43") /*创建人*/,
        component: "Selector",
        props: {
          placeholder: messages("common.please.input") /*请输入*/ + messages("finance-10.key44") /*姓名/工号*/,
          selectorItem: {
            ...selectorData["user"],
            url: `/api/users/v3/search?page=0&size=9999&roleType=TENANT&status=all`,
            label: (record) =>
              `${record.employeeID}-${record.fullName}${
                record.status !== 1001
                  ? `（${
                      record.status === 1002
                        ? messages("finance-1.key91") /*待离职员工*/
                        : messages("finance-1.key92") /*离职员工*/
                    }）`
                  : ""
              }`,
          },
        },
      },
      {
        id: "createdDate",
        label: messages("finance-10.key45") /*创建日期*/,
        component: "DateRangePicker",
        parser: (value) => ({
          createdDateFrom: value && value[0] ? moment(value[0]).format("YYYY-MM-DD 00:00:00") : undefined,
          createdDateTo: value && value[1] ? moment(value[1]).format("YYYY-MM-DD 23:59:59") : undefined,
        }),
        initialValue: [moment().subtract(1, "month"), moment()],
      },
      {
        id: "bookDate",
        label: messages("finance-10.key29") /*预提记账日期*/,
        component: "DateRangePicker",
        parser: (value) => ({
          bookDateFrom: value && value[0] ? moment(value[0]).format("YYYY-MM-DD 00:00:00") : undefined,
          bookDateTo: value && value[1] ? moment(value[1]).format("YYYY-MM-DD 23:59:59") : undefined,
        }),
        initialValue: [moment().subtract(1, "month"), moment()],
      },
    ],
    rowSelection: {
      selectedRowKeys: [],
      onChange: this.onSelectChange,
      onSelect: this.onSelectItem,
      onSelectAll: this.onSelectAll,
    },
    selectedData: [],
    loading: false,
    templateCodeList: [],
  };

  judgeCertificate = (setOfBooksId) => {
    this.setState({ loading: true });
    Promise.all([expenseService.getAccountFlag(), expenseService.getCertificatePreviewTab(setOfBooksId, "ACCRUED_EXP")])
      .then((res) => {
        const [flag, ledger] = res;
        let templateCodeList = [];
        if (ledger.data && Array.isArray(ledger.data) && flag.data) {
          templateCodeList = ledger.data
            .filter((i) => i.templateCode === "GL_ACCRUED" && i.isEnable === true)
            .map((i) => i.templateCode);
        }
        this.columns.find((item) => item.dataIndex === "operation").render = (value, record) => (
          <span>
            {templateCodeList.length > 0 && (
              <span>
                <a onClick={() => this.onViewCredential(record)}>{messages("finance-10.key49") /*预览凭证*/}</a>
                <span className="ant-divider" />
              </span>
            )}
            <a onClick={() => this.onViewDetail(record)}>{messages("finance-10.key31") /*查看明细*/}</a>
            <span className="ant-divider" />
            <a onClick={() => this.onViewTotal(record)}>{messages("finance-10.key32") /*查看汇总*/}</a>
          </span>
        );
        this.setState({ templateCodeList, loading: false });
      })
      .catch((e) => {
        this.setState({ loading: false });
        message.error(e.response.data.message);
      });
  };

  handleChangeSetOfBook = (value, isTitle) => {
    const { searchForm } = this.state;
    let setOfBooksId = searchForm.find((item) => item.id === "companyId").props.listExtraParams.setOfBooksId;
    if (setOfBooksId !== value.id) {
      if (!isTitle) {
        this.advancedTableRef.advancedSearchRef.props.form.setFieldsValue({
          companyId: undefined,
        });
      }
      searchForm.map((item) => {
        if (item.id === "companyId") {
          item.props.listExtraParams = {
            setOfBooksId: value.id,
            enabled: true,
          };
        }
      });
      this.setState({ searchForm });
    }
  };

  columns = [
    { title: messages("finance-10.key26") /*批次号*/, dataIndex: "batchNumber" },
    { title: messages("finance-10.key27") /*批次账套*/, dataIndex: "setOfBooksName", width: 240, minWidth: 180 },
    { title: messages("finance-10.key28") /*批次公司*/, dataIndex: "companyName", width: 240, minWidth: 180 },
    {
      title: messages("finance-10.key45") /*创建日期*/,
      dataIndex: "createdDate",
      stableWidth: 120,
      render: (value) => (value ? moment(value).format("YYYY-MM-DD") : "-"),
    },
    {
      title: messages("finance-10.key46") /*创建人|工号*/,
      dataIndex: "operator",
      render: (value) => `${value.fullName}|${value.employeeID}`,
    },
    { title: messages("finance-10.key47") /*本币币种*/, dataIndex: "baseCurrencyCode", stableWidth: 100 },
    {
      title: messages("finance-10.key48") /*本币总预提金额*/,
      dataIndex: "baseAmount",
      render: (value, record) => this.filterMoney(value, queryCurrencyPrecision(record.baseCurrencyCode)),
    },
    {
      title: messages("finance-10.key29") /*预提记账日期*/,
      dataIndex: "bookDate",
      render: (value, record) => (
        <EditDate
          value={moment(value)}
          onChange={(value) => this.handleEditRecord(value, record, "bookDate")}
          startDate={record.bookDateFrom}
          endDate={record.bookDateTo}
        />
      ),
    },
    {
      title: messages("finance-10.key30") /*预提冲销记账日期*/,
      dataIndex: "reverseBookDate",
      render: (value, record) => (
        <EditDate
          value={moment(value)}
          onChange={(value) => this.handleEditRecord(value, record, "reverseBookDate")}
          startDate={record.reverseBookDateFrom}
          endDate={record.reverseBookDateTo}
        />
      ),
    },
    {
      title: messages("common.operation") /*操作*/,
      dataIndex: "operation",
      minWidth: 120,
      render: (value, record) => (
        <span>
          <a onClick={() => this.onViewCredential(record)}>{messages("finance-10.key49") /*预览凭证*/}</a>
          <span className="ant-divider" />
          <a onClick={() => this.onViewDetail(record)}>{messages("finance-10.key31") /*查看明细*/}</a>
          <span className="ant-divider" />
          <a onClick={() => this.onViewTotal(record)}>{messages("finance-10.key32") /*查看汇总*/}</a>
        </span>
      ),
    },
  ];

  handleEditRecord = (value, record, type) => {
    this.setState({ loading: true });
    httpFetch
      .post(`/api/accrued/expense/batch/review/edit`, {
        ...record,
        [type]: value,
      })
      .then(() => {
        this.setState({ loading: false }, this.advancedTableRef.getList);
      })
      .catch((e) => {
        this.setState({ loading: false });
        message.error(e.response.data.message);
      });
  };

  onViewCredential = (record) => {
    const { templateCodeList } = this.state;
    Credential.open({ record, templateCodeList }, this);
  };

  onViewDetail = (record) => {
    this.context.router.push(
      menuRoute.getRouteItem("detail-view").url.replace(":accruedExpenseBatchId", record.accruedExpenseBatchId)
    );
  };

  onViewTotal = (record) => {
    this.context.router.push(
      menuRoute.getRouteItem("total-view").url.replace(":accruedExpenseBatchId", record.accruedExpenseBatchId)
    );
  };

  searchParams = {};

  service = (page, size, searchParams) => {
    this.searchParams = searchParams;
    return httpFetch.post(`/api/accrued/expense/batch/review/query`, {
      page,
      size,
      ...searchParams,
    });
  };

  handleConfirm = () => {
    Modal.confirm({
      title: messages("finance-10.key50") /*确认通过*/,
      content: messages("finance-10.key51") /*是否确定通过并生成凭证？*/,
      onOk: this.handleOk,
    });
  };

  handleOk = () => {
    const { selectedData, rowSelection } = this.state;
    this.setState({ loading: true });
    httpFetch
      .post(`/api/accrued/expense/batch/review/pass`, {
        accruedExpenseBatchIds: selectedData.map((item) => item.accruedExpenseBatchId),
      })
      .then(() => {
        rowSelection.selectedRowKeys = [];
        this.setState({ loading: false, selectedData: [], rowSelection }, this.advancedTableRef.getList);
      })
      .catch((e) => {
        this.setState({ loading: false });
        message.error(e.response.data.message);
      });
  };

  handleConfirmReject = () => {
    Modal.confirm({
      title: messages("finance-10.key52") /*确认驳回*/,
      content: messages("finance-10.key53") /*是否确定驳回？*/,
      onOk: this.handleReject,
    });
  };

  handleReject = () => {
    const { selectedData, rowSelection } = this.state;
    this.setState({ loading: true });
    httpFetch
      .post(`/api/accrued/expense/batch/review/reject`, {
        accruedExpenseBatchIds: selectedData.map((item) => item.accruedExpenseBatchId),
      })
      .then(() => {
        rowSelection.selectedRowKeys = [];
        this.setState({ loading: false, selectedData: [], rowSelection }, this.advancedTableRef.getList);
      })
      .catch((e) => {
        this.setState({ loading: false });
        message.error(e.response.data.message);
      });
  };

  handleSearch = (pagination, values) => {
    if (values.setOfBooksId !== this.searchParams.setOfBooksId) {
      this.judgeCertificate(values.setOfBooksId);
    }
  };

  render() {
    const { rowSelection, loading, searchForm } = this.state;
    return (
      <AdvancedTable
        service={this.service}
        index
        title={messages("finance-10.key54") /*预提复核*/}
        tableName={"accrual-management-recheck"}
        columns={this.columns}
        searchForm={searchForm}
        propsLoading={loading}
        rowKey="accruedExpenseBatchId"
        rowSelection={rowSelection}
        onRef={(ref) => (this.advancedTableRef = ref)}
        pageCacheEnable={false}
        onSearch={this.handleSearch}
        footer={
          <Space>
            <Button onClick={this.handleConfirm}>{messages("common.pass") /*通过*/}</Button>
            <Button onClick={this.handleConfirmReject}>{messages("common.reject") /*驳回*/}</Button>
          </Space>
        }
      />
    );
  }
}

AccrualManagementRecheck.contextTypes = {
  router: React.PropTypes.object,
};

function mapStateToProps(state) {
  return {
    company: state.login.loginCompany,
  };
}

export default connect(mapStateToProps)(AccrualManagementRecheck);
